<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>2-处理ajax响应</title>
  <style>
    #box {
      width: 200px;
      height: 200px;
      border: 1px solid #666;
    }
  </style>
</head>
<body>
  <button id="textBtn">AJAX 获取Text</button>
  <button id="jsonBtn">AJAX 获取JSON</button>

  <div id="box"></div>
  <script>
    document.querySelector('#textBtn').onclick = () => {
      let xhr = new XMLHttpRequest();
      xhr.open('get', 'http://localhost:8081/text-server');
      xhr.send();
      
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          console.log(xhr.status);
          console.log(xhr.getResponseHeader("Content-Type"));
          let text = xhr.responseText;
          document.getElementById('box').innerHTML = text;
        }
      }
    }

    document.querySelector('#jsonBtn').onclick = () => {
      let xhr = new XMLHttpRequest();
      xhr.open('get', 'http://localhost:8081/json-server');
      xhr.send();
      // 自动解析为js对象
      xhr.responseType = "json";
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          console.log(xhr.status);
          console.log(xhr.getResponseHeader("Content-Type"));
          // let text = xhr.responseText;
          // 手动将JSON文本,转js对象
          // let obj = JSON.parse(text)
          let obj = xhr.response;
          document.getElementById('box').innerHTML = JSON.stringify(obj);
         
        }
      }
    }
  </script>
</body>
</html>